package com.happe.foodeasy.manage.controller;

import com.happe.foodeasy.manage.image.entity.ImagePhotoEntity;
import com.happe.foodeasy.manage.service.ImagePhotoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
@RequestMapping("/imagePhoto")
public class ImagePhotoController {
    @Autowired
    private ImagePhotoService imagePhotoService;

    @RequestMapping("/firstImage.do")
    public void findFirstImage(long commodityId, HttpServletResponse response) {
        ImagePhotoEntity imagePhotoEntity = imagePhotoService.findFirstTargetCommodityImage(commodityId);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            if (imagePhotoEntity != null) {
                outputStream.write(imagePhotoEntity.getPhotoByte());
            } else {
                write404File(outputStream);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void write404File(ServletOutputStream output) throws IOException {
        String file404 = this.getClass().getResource("/404.jpg").getPath();
        FileInputStream in = new FileInputStream(file404);
        byte[] buff = new byte[1024];
        int len = 0;
        while ((len = in.read(buff)) != -1) {
            output.write(buff, 0, len);
        }
    }
}
